<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2020-09-05
 * Time: 16:54
 */

namespace extend\payment;


class FuYouMerchant
{
    public $domain = '';
    public $privateKey = '';


    /**
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public function updateMerchant($request)
    {
        // 获取支付参数
        $paramSign = $this->beforeRequest($request);
        // 接口地址
        $urlApi = "wxMchntUpd";

        // 必填数据
        $paramSign["fy_mchnt_cd"] = $request["fy_mchnt_cd"];
        !empty($request['settle_tp']) ? $paramSign["settle_tp"] = $request['settle_tp'] : false;


        $response = $this->sendRequest($urlApi, $paramSign);
var_dump($response);
exit;
        return $this->afterRequest($response);
    }

    /**
     * 请求前操作
     * @param array $request
     * @return mixed
     */
    public function beforeRequest($request = [])
    {
//        $this->domain = $request['domain'];

        $this->domain = $request['domain'];
        $this->privateKey = $request['private_key'];
        $paramSign["ins_cd"] = $request["ins_cd"];
        $paramSign["trace_no"] = $request["trace_no"];

        return $paramSign;
    }

    /**
     * 发送请求
     * @param $url
     * @param $paramSign
     * @param array $paramAttach
     * @return string
     */
    public function sendRequest($url, $paramSign)
    {
        // 链接
        $url = $this->domain . $url;
        $privateKey = $this->privateKey;

        // 改变编码，传成GBK
        $paramSign = array2GBK($paramSign);

        // RSAwithMD5+base64加密后得到的sign
        $paramSign['sign'] = strtolower(md5(sortAndCombine($paramSign)."&key={$privateKey}"));
//var_dump(sortAndCombine($paramSign));
//exit;
        $paramSign = "<?xml version=\"1.0\" encoding=\"GBK\" standalone=\"yes\"?><xml>" . arrayToXml2($paramSign) . "</xml>";
var_dump($paramSign);

        // 经过两次urlencode()之后的字符串
        $paramSign = 'req=' . urlencode(urlencode($paramSign));

        // 过滤url
        $url = str_replace(' ', '+', $url);
        var_dump($url);
        var_dump($paramSign);

        //返回的xml字符串
        $response = urldecode(postRequest($url, $paramSign));
        return $response;
    }

    public function afterRequest($response)
    {
        $response = json_decode($response, true);

        var_dump($response);
    }
}